package com.jic.manager.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.base.vo.enums.DeptTypeEnums;
import com.jic.enums.RedisKey;
import com.jic.manager.common.service.ManagerBaseService;
import com.jic.manager.common.util.BeanUtil;
import com.jic.manager.entity.*;
import com.jic.manager.enums.DeptTypeEnum;
import com.jic.manager.exception.AppRuntimeException;
import com.jic.manager.mapper.SysDeptMapper;
import com.jic.manager.mapper.SysRoleUserMapper;
import com.jic.manager.mapper.SysUserDeptMapper;
import com.jic.manager.mapper.SysUserMapper;
import com.jic.manager.request.*;
import com.jic.manager.request.orgcenter.SysDeptTreeRequest;
import com.jic.manager.response.MemMerchantInfoResponse;
import com.jic.manager.response.MemStoreResponse;
import com.jic.manager.response.MerchantResponse;
import com.jic.manager.response.SysDeptResponse;
import com.jic.manager.service.MerchantService;
import com.jic.manager.service.MestoreService;
import com.jic.manager.service.SysDeptService;
import com.jic.manager.utils.RedisManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 部门信息表
 * @author :
 * @email :
 * @since : 2020-02-26 09:39:35
 * @version : v1.0.0
 */
@Component
@Slf4j
public class SysDeptServiceImpl extends ManagerBaseService implements SysDeptService {

    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private MestoreService mestoreService;
    @Autowired
    private MerchantService merchantService;
    @Resource
    private SysUserDeptMapper sysUserDeptMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysRoleUserMapper sysRoleUserMapper;
    @Resource
    private RedisManager redisManager;

    @Override
    public long insert(SysDept sysDept) {
        long flag = sysDeptMapper.insert(sysDept);
        return flag;
    }

    @Override
    public long delete(Long id) {
        return sysDeptMapper.delete(id);
    }

    @Override
    public long update(SysDept sysDept) {
        return sysDeptMapper.update(sysDept);
    }

    @Override
    public SysDept queryByPrimaryKey(Long id){
        return sysDeptMapper.queryByPrimaryKey(id);
    }

    @Override
    public List<SysDept> query(SysDept sysDept){
        return sysDeptMapper.query(sysDept);
    }

    @Override
    public PageResult<SysDept> queryPage(SysDept sysDept, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<SysDept> list = sysDeptMapper.queryPage(startIndex, pageQuery.getLimit(), sysDept);
        long count = sysDeptMapper.queryPageCount(sysDept);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public RestResult<List<SysDeptResponse>> findDeptTree(SysDept sysDept) {
        try {
            List<SysDeptResponse> sysDepts = new ArrayList<>();
            List<SysDept> depts = sysDeptMapper.query(sysDept);
            if (sysDept.getDeptType() != null && sysDept.getDeptType() == 1L){
                List<SysDept> sysDepts1 = sysDeptMapper.query(new SysDept() {{
                    setDeptType(2);
                    setDeleteFlag(0);
                }});
                depts.addAll(sysDepts1);
            }
            for (SysDept dept : depts) {
                if (dept.getPid() == 0) {
                    SysDeptResponse sysDeptResponse = new SysDeptResponse();
                    BeanUtils.copyProperties(dept,sysDeptResponse);
                    sysDeptResponse.setLevel(0);
                    sysDepts.add(sysDeptResponse);
                }
            }
            findChildren(sysDepts, depts);
            return RestResult.success(sysDepts);
        }catch (Exception e){
            // TODO
            e.printStackTrace();
            return RestResult.error("9999",e.getLocalizedMessage());
        }
    }

    @Override
    public RestResult<String> editDeptInfo(SysDept sysDept) {
        try{
            Long id = sysDept.getId();
            if (id != null && id != 0){
                sysDeptMapper.update(sysDept);
            }else{
                //如果pid != 0 && type == 1 店铺
                if(sysDept.getPid() != 0 && DeptTypeEnum.STORE_TYPE.getType().equals(sysDept.getDeptType())){
                    //新增店铺数据
                    mestoreService.insert(new Mestore(){{
                        setStoreName(sysDept.getDeptName());
                    }});
                }else if(sysDept.getPid() == 0 && DeptTypeEnum.MERCHANT_TYPE.getType().equals(sysDept.getDeptType())){
                    //新增商家数据
                    merchantService.insert(new Merchant(){{
                        setName(sysDept.getDeptName());
                    }});
                }
                //TODO 创建人
                sysDept.setCreateTime(new Date());
//                sysDept.setIsDelete("N");
                sysDeptMapper.insert(sysDept);
            }
            return RestResult.success("新增机构成功");
        }catch (Exception e){
            e.printStackTrace();
            return RestResult.error("9999","【机构】保存失败！！！"+e.getLocalizedMessage());
        }
    }

    @Override
    public RestResult<String> deleteDept(String ids) {
        try{
            if(StringUtils.isEmpty(ids)) {
                throw new Exception("必传参数ids为空!");
            }
            String[] idList = ids.split(",");
            for (String id : idList) {
                sysDeptMapper.delete(Long.valueOf(id));
            }
            return RestResult.success("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return RestResult.error("9999","【机构】删除失败！！！"+e.getLocalizedMessage());
        }
    }

    @Override
    public Long insertSysDept(SysDept sysDept) {
        sysDeptMapper.insert(sysDept);
        return sysDept.getId();
    }

    @Override
    public RestResult<Boolean> saveDeptList(SaveDeptListRequest saveDeptListRequest) {
        try {

            log.info("批量新增组织机构=>>>>>>>>>>>>>>>>>>>>{}", JSONArray.toJSONString(saveDeptListRequest));
            List<SysDept> sysDeptList = new ArrayList<>();
            SysDept sysDeptRest = new SysDept();

            if (null != saveDeptListRequest.getPBusinessId() && saveDeptListRequest.getDeptType() != 1){
                //查询子平台活商家平台
                if (DeptTypeEnums.MERCHANT_PLATFORM.getCode().equals(saveDeptListRequest.getDeptType())){
                    //查询上级子平台
                    List<SysDept> childList = sysDeptMapper.query(new SysDept() {{
                        setDeptType(DeptTypeEnums.CHILD_PLATFORM.getCode());
                        setBusinessId(saveDeptListRequest.getPBusinessId());
                    }});
                    if (CollectionUtils.isEmpty(childList)){
                        throw new RuntimeException("子平台不存在");
                    }
                    sysDeptRest = childList.get(0);
                }else if (DeptTypeEnums.STORE_PLATFORM.getCode().equals(saveDeptListRequest.getDeptType())){
                    //查询上级商家
                    List<SysDept> merchantList = sysDeptMapper.query(new SysDept() {{
                        setDeptType(DeptTypeEnums.MERCHANT_PLATFORM.getCode());
                        setBusinessId(saveDeptListRequest.getPBusinessId());
                    }});
                    if (CollectionUtils.isEmpty(merchantList)){
                        throw new RuntimeException("商家不存在");
                    }
                    sysDeptRest = merchantList.get(0);
                }
            }else{}
            SysDept finalSysDeptRest = sysDeptRest;
            saveDeptListRequest.getSaveDeptListRequestListList().forEach(item->{
                SysDept sysDept = new SysDept();
                if (0 == saveDeptListRequest.getPBusinessId()){
                    //卡奥斯运营平台
                    sysDept.setPid(179L);
                }else{
                    sysDept.setPid(finalSysDeptRest.getId());
                }
                sysDept.setDeptType(saveDeptListRequest.getDeptType());
                sysDept.setDeptName(item.getDeptName());
                sysDept.setBusinessId(item.getBusinessId());
                sysDept.setStatus("0");
                sysDept.setDeleteFlag(0);
                sysDept.setCreateTime(new Date());
                sysDeptMapper.insert(sysDept);
            });
            return RestResult.success(true);
        }catch (RuntimeException e){
            log.error("批量新增组织架构失败==><>>>>>{}",e.getMessage());
            return RestResult.error("9999","服务器异常...");
        }
    }

    @Override
    public Boolean saveDeptListStore(SaveDeptListRequest saveDeptListRequest) {
        try {
            saveDeptListRequest.getSaveDeptListRequestListList().forEach(item->{
                List<SysDept> merchantList = sysDeptMapper.query(new SysDept() {{
                    setDeptType(DeptTypeEnums.MERCHANT_PLATFORM.getCode());
                    setBusinessId(item.getPBusinessId());
                }});
                if (CollectionUtils.isNotEmpty(merchantList)){
                    SysDept sysDept = new SysDept();
                    sysDept.setPid(merchantList.get(0).getId());
                    sysDept.setDeptType(DeptTypeEnums.STORE_PLATFORM.getCode());
                    sysDept.setDeptName(item.getDeptName());
                    sysDept.setBusinessId(item.getBusinessId());
                    sysDept.setStatus("0");
                    sysDept.setDeleteFlag(0);
                    sysDept.setCreateTime(new Date());
                    sysDeptMapper.insert(sysDept);
                }
            });
            return true;
        }catch (RuntimeException e){
            log.error("批量新增组织架构失败==><>>>>>{}",e.getMessage());
            return false;
        }
    }

    @Override
    public RestResult<List<Long>> getUccUserAuthor(SysUserDept sysUserDept) {
        try {
            List<Long> rest = sysUserDeptMapper.getUccUserAuthor(sysUserDept.getUserId(),sysUserDept.getDeptType());
            return RestResult.success(rest);
        }catch (Exception e){
            log.error("查询用户数据权限错误==>>>>{}",e.getMessage());
            return RestResult.error("9999","服务器异常...");
        }
    }

    @Override
    public RestResult<List<Long>> getChilderByPid(SysDept sysDept) {
        try {
            List<Long> restIds = new ArrayList<>();
            List<SysDept> childeListrByPid = sysDeptMapper.getChildeListrByPid(sysDept.getPid());
            childeListrByPid.forEach(item->{
                restIds.add(item.getId());
            });
            return RestResult.success(restIds);
        }catch (Exception e){
            log.error("查询子级树失败==>>>>{}",e.getMessage());
            return RestResult.error("9999","服务器错误");
        }
    }


    @Override
    public RestResult<List<SysDeptResponse>> getChildeListrByPid(Long deptId){
        try {
            List<SysDeptResponse> restList = new ArrayList<>();
            List<SysDept> rest = sysDeptMapper.getChildeListrByPid(deptId);
            for (SysDept dept : rest) {
                if (deptId.equals(dept.getId())) {
                    SysDeptResponse sysDeptResponse = new SysDeptResponse();
                    BeanUtils.copyProperties(dept,sysDeptResponse);
                    sysDeptResponse.setLevel(0);
                    restList.add(sysDeptResponse);
                }
            }
            findChildren(restList, rest);
            return RestResult.success(restList);
        }catch (Exception e){
            log.error("查询子级树失败==>>>>{}",e.getMessage());
            return RestResult.error("9999","服务器错误");
        }
    }

    @Override
    public Boolean updateChildUserAllStatus(Long childId, Integer status) {
        try {
            //根据子平台 查询下级的id
            List<Long> childIdList = sysDeptMapper.queryChildIdList(childId);
            childIdList.forEach(deptId->{
                //修改用户状态
                sysUserMapper.updateStatus(deptId,status.toString());
                //查询用户
                if(status == 0){
                    List<SysUser> sysUserList = sysUserMapper.query(new SysUser() {{
                        setDeptId(deptId);
                        setDeleteFlag(0);
                    }});
                    sysUserList.forEach(sysUser -> {
                        //如果停用 删除redis登录缓存
                        Set<String> keys = redisManager.getKeys(RedisKey.UUC_TOKEN.getName()+sysUser.getId());
                        log.info("==================================>>>>>{}", JSONArray.toJSONString(keys));
                        if (CollectionUtils.isNotEmpty(keys)){
                            for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
                                String string = (String) iterator.next();
                                System.out.println(string);
                                try {
                                    redisManager.del(string);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
                }
            });
            return true;
        }catch (Exception e){
            log.error("停用启用 失败",e.getLocalizedMessage());
            return false;
        }
    }

    @Transactional
    @Override
    public RestResult<Boolean> updateUserAuthor(UserAuthorRequest uccUserAuthorRequest) {
        try {
            //修改用户角色
            sysUserMapper.update(new SysUser(){{
                setId(uccUserAuthorRequest.getId());
                setRoleid(uccUserAuthorRequest.getRoleid());
                setUpdateTime(new Date());
            }});
            //删除用户角色关联
            sysRoleUserMapper.deleteByUserId(uccUserAuthorRequest.getId());

            sysRoleUserMapper.insert(new SysRoleUser(){{
                setRoleid(uccUserAuthorRequest.getRoleid());
                setUserid(uccUserAuthorRequest.getId());
                setStatus("0");
            }});

            //删除用户的所有权限
            sysUserDeptMapper.deleteByUserId(uccUserAuthorRequest.getId());
            //新增用户权限
            uccUserAuthorRequest.getDeptIdList().forEach(userDeptId->{
                SysDept sysDept = sysDeptMapper.queryByPrimaryKey(userDeptId);
                if(null != sysDept){
                    sysUserDeptMapper.insert(new SysUserDept(){{
                        setDeptId(sysDept.getId());
                        setDeptType(sysDept.getDeptType());
                        setBusinessId(sysDept.getBusinessId());
                        setUserId(uccUserAuthorRequest.getId());
                        setCreateTime(new Date());
                        setCreator(uccUserAuthorRequest.getAdminOperate().getOperator());
                        setCreatorName(uccUserAuthorRequest.getAdminOperate().getOperateName());
                        setDeleteFlag(0);
                    }});
                }
            });
            return RestResult.success(true);
        }catch (RuntimeException e){
            log.error("修改用户权限错误....."+e);
            return RestResult.error("9999","服务器错误...");
        }
    }

    @Transactional
    @Override
    public RestResult<Boolean> updateDeptName(UpdateDeptNameRequest updateDeptNameRequest) {
        try {
            //根据业务ID和业务类型查询
            List<SysDept> sysDeptList = sysDeptMapper.query(new SysDept() {{
                setBusinessId(updateDeptNameRequest.getBusinessId());
                setDeptType(updateDeptNameRequest.getDeptType());
                setDeleteFlag(0);
            }});
            if(CollectionUtils.isEmpty(sysDeptList)){
                return RestResult.error("9999","当前组织架构不存在 business_id = "+updateDeptNameRequest.getBusinessId());
            }
            //修改
            sysDeptMapper.update(new SysDept(){{
                setId(sysDeptList.get(0).getId());
                setDeptName(updateDeptNameRequest.getDeptName());
                setUpdateTime(new Date());
            }});
            return RestResult.success(true);
        }catch (Exception e){
            log.error("修改组织机构名称失败==>>>>>>{}",e.getLocalizedMessage());
            return RestResult.error("9999","服务器错误...");
        }
    }


    private void findChildren(List<SysDeptResponse> sysDepts, List<SysDept> depts) {
        for (SysDeptResponse sysDept : sysDepts) {
            List<SysDeptResponse> children = new ArrayList<>();
            for (SysDept dept : depts) {
                if (sysDept.getId().equals(dept.getPid())) {
                    SysDeptResponse sysDeptResponse = new SysDeptResponse();
                    BeanUtils.copyProperties(dept,sysDeptResponse);
                    sysDeptResponse.setParentName(sysDept.getDeptName());
                    sysDeptResponse.setLevel(sysDept.getLevel()+1);
                    children.add(sysDeptResponse);
                }
            }
            sysDept.setChildren(children);
            findChildren(children, depts);
        }
    }


    @Override
    public RestResult<List<SysDeptResponse>> getAuthorDeptTree (SysDeptTreeRequest sysDeptTreeRequest) {
        try {
            List<SysDeptResponse> sysDeptList = new ArrayList<>();
            List<SysDept> deptList = sysDeptMapper.queryTree(sysDeptTreeRequest);
            for (SysDept dept : deptList) {
                if (dept.getId().equals(sysDeptTreeRequest.getAdminOperate().getDeptId())) {
                    SysDeptResponse sysDeptResponse = new SysDeptResponse();
                    BeanUtils.copyProperties(dept,sysDeptResponse);
                    sysDeptResponse.setLevel(0);
                    if(dept.getDeptType() != 0){
                        //查询父级
                        SysDept sysDept = sysDeptMapper.queryByPrimaryKey(dept.getPid());
                        sysDeptResponse.setParentName(sysDept.getDeptName());
                    }
                    sysDeptList.add(sysDeptResponse);
                }
            }
            findChildren(sysDeptList, deptList);
            return RestResult.success(sysDeptList);
        }catch (Exception e){
            log.error("查询组织机构失败==>>>{}",e);
            return RestResult.error("9999",e.getLocalizedMessage());
        }
    }

    @Override
    public RestResult<String> queryDeptNameById(Long deptId) {
        return executeQuery(() -> {
            SysDept sysDept = sysDeptMapper.queryByPrimaryKey(deptId);
            if(null != sysDept){
                return sysDept.getDeptName();
            }
            return null;
        });
    }

    @Override
    public List<Long> queryChildListById(Long deptId) {
        List<Long> childList = sysDeptMapper.queryChildListById(deptId);
        return childList;
    }


    @Override
    public RestResult<Long> updateMerchantScopeApplicationById(MerchantRequest merchantRequest) {
        RestResult result = new RestResult();
        Merchant merchant = new Merchant();
        merchant.setId(merchantRequest.getId());
        merchant.setScopeApplication(merchantRequest.getScopeApplication());
        merchant.setWhetherApplication(merchantRequest.getWhetherApplication());
        Long flag = merchantService.update(merchant);
        if(flag != 0){
            result.setData(flag);
            result.setCode("0000");
        }else {
            log.error("修改失败");
            result.setCode("9999");
        }
        return  result;

    }

    @Override
    public MemMerchantInfoResponse getGrowhtScopeInfo(Long merchantId) {
        MemMerchantInfoResponse merchantInfoResponseRestResult = merchantService.getGrowhtScopeInfo(merchantId);
        return merchantInfoResponseRestResult;
    }


    /*
     * 根据商家或者店铺查询所属子平台名称
     * */
    @Override
    public RestResult<String> queryChildNameById(Long deptId) {
        return executeQuery(() -> {
            SysDept sysDept = sysDeptMapper.queryByPrimaryKey(deptId);
            if(null != sysDept){
                if (sysDept.getDeptType() == 3){
                    SysDept merchant = sysDeptMapper.queryByPrimaryKey(sysDept.getPid());
                    if (null !=merchant && merchant.getDeptType()==2){
                        SysDept child = sysDeptMapper.queryByPrimaryKey(sysDept.getPid());
                        if (null !=child){
                            return child.getDeptName();
                        }
                    }
                }else if (sysDept.getDeptType() == 2) {
                    SysDept child = sysDeptMapper.queryByPrimaryKey(sysDept.getPid());
                    if (null !=child){
                        return child.getDeptName();
                    }
                }else if (sysDept.getDeptType() == 1){
                    SysDept parent = sysDeptMapper.queryByPrimaryKey(sysDept.getPid());
                    if (null !=parent){
                        return parent.getDeptName();
                    }
                }else {
                    return sysDept.getDeptName();
                }

            }
            return null;
        });
    }


    @Override
    public RestResult<Long> getDeptIdByMsName(String msName) {
        RestResult result = new RestResult();
        Long deptId = sysDeptMapper.getDeptIdByMsName(msName);
        result.setData(deptId);
        return result;
    }


    /*
     * */
    @Override
    public RestResult checkApplication(Long deptid){
        RestResult result = new RestResult();
        //没有设置适用范围 商家登录
        if (null != deptid) {
            SysDept sysDept = sysDeptMapper.queryByPrimaryKey(deptid);
            if (null != sysDept) {
                //商家
                if(sysDept.getDeptType() == 2){
                    Merchant merchant = merchantService.queryByPrimaryKey(sysDept.getBusinessId());
                    if (null != merchant) {
                        if (null == merchant.getScopeApplication()){
                            result.setMsg("请先设置【等级适用范围】，之后按照权限进行操作");
                        }else if (null != merchant.getScopeApplication() && merchant.getScopeApplication()== 2){
                            result.setMsg("【等级适用范围】已设置为店铺，无法操作");
                        }
                    }
                    //店铺
                }else if (sysDept.getDeptType() == 3){
                    SysDept sysDeptquery = sysDeptMapper.queryByPrimaryKey(sysDept.getPid());
                    if (null != sysDeptquery) {
                        Merchant merchant = merchantService.queryByPrimaryKey(sysDeptquery.getBusinessId());
                        if (null != merchant) {
                            if (null == merchant.getScopeApplication()){
                                result.setMsg("请先设置【等级适用范围】，之后按照权限进行操作");
                                result.setData(1);
                            }else if (null != merchant.getScopeApplication() && merchant.getScopeApplication()== 1){
                                result.setMsg("【等级适用范围】已设置为商家，无法操作");
                                result.setData(1);
                            }
                        }
                    }

                }
            }

        }
        return result;
    }

    @Override
    public List<Long> querymMerchantOrStoreListById(Long deptId) {
        List<Long> merchantOrStoreList = new ArrayList<>();
        SysDeptTreeRequest sysDeptTreeRequest=new SysDeptTreeRequest();
        if(null !=deptId){
            merchantOrStoreList = sysDeptMapper.queryMerchantIdList(deptId);
            Iterator<Long> it = merchantOrStoreList.iterator();
            while(it.hasNext()) {
                Long value = it.next();
                if(value.equals(deptId)) {
                    it.remove();
                }
            }
        }
        return merchantOrStoreList;
    }

    @Override
    public Long getDeptIdByMsId(SysDeptRequest sysDept) {
        SysDept sysDept1 = new SysDept();
        sysDept1.setDeptType(sysDept.getDeptType());
        sysDept1.setId(sysDept.getId());
        return sysDeptMapper.getDeptIdByMsId(sysDept1);
    }
    public List<Long> querymMerchantOrStoreListByName(String name) {
        List<Long> list = new ArrayList<>();
        SysDept sysDept = new SysDept();
        if(name !=""){
            sysDept.setDeptType(1);
            sysDept.setDeptName(name);
            List<SysDept> sysDeptList = sysDeptMapper.queryBlurred(sysDept);
            sysDeptList.forEach(items->{
                list.add(items.getId());
            });

        }
        return list;
    }

    @Override
    public RestResult<String> queryChildNameByDeptId(ChildNameRequest childNameRequest) {
        return executeQuery(() -> {
            if (childNameRequest.getDeptType() == 3){
                SysDept sysDept = sysDeptMapper.queryByPrimaryKey(childNameRequest.getDeptId());
                if (null !=sysDept ){
                    SysDept merchant = sysDeptMapper.queryByPrimaryKey(sysDept.getPid());
                    if (null !=merchant && merchant.getDeptType()==2){
                        SysDept child = sysDeptMapper.queryByPrimaryKey(merchant.getPid());
                        if (null !=child){
                            return child.getDeptName();
                        }
                    }
                }
            }else if (childNameRequest.getDeptType() == 2) {
                SysDept merchant = sysDeptMapper.queryByPrimaryKey(childNameRequest.getDeptId());
                if (null !=merchant){
                    SysDept child = sysDeptMapper.queryByPrimaryKey(merchant.getPid());
                    if (null !=child){
                        return child.getDeptName();
                    }
                }
            }
            return null;
        });
    }

    @Override
    public List<SysDeptResponse> getUserProviderAuthorDept(Long userId, Long deptId) {
        List<SysDept> deptList = sysDeptMapper.queryUserProviderAuthorDept(userId, deptId);
        List<SysDeptResponse> sysDeptList = deptList.stream().map(temp -> {
            SysDeptResponse sysDeptResponse = BeanUtil.copy(temp, SysDeptResponse.class);
            return sysDeptResponse;
        }).filter(item -> item != null).collect(Collectors.toList());
        return sysDeptList;
    }

    @Override
    public RestResult<List<SysDeptResponse>> getDeptList(SysDeptTreeRequest sysDeptTreeRequest) {
        try {
            List<SysDeptResponse> sysDeptList = new ArrayList<>();
            SysDept sysDept = sysDeptMapper.queryByPrimaryKey(sysDeptTreeRequest.getAdminOperate().getDeptId());
            if (sysDept != null) {
                SysDeptResponse sysDeptResponse = new SysDeptResponse();
                BeanUtil.copy(sysDept, sysDeptResponse);
                sysDeptList.add(sysDeptResponse);
                List<SysDept> sysDepts = sysDeptMapper.getChildDeptList(sysDeptTreeRequest.getAdminOperate().getOperator(),sysDeptTreeRequest.getAdminOperate().getDeptId());
                if (CollectionUtils.isNotEmpty(sysDepts)) {
                    List<SysDeptResponse> sysDeptResponseList = new ArrayList<>();
                    for (SysDept sysDept2 : sysDepts) {
                        SysDeptResponse sysDeptResponse1 = new SysDeptResponse();
                        BeanUtil.copy(sysDept2, sysDeptResponse1);
                        sysDeptList.add(sysDeptResponse1);
                    }
                }
            }
            return RestResult.success(sysDeptList);
        } catch (Exception e) {
            log.error("查询母平台和所有子平台==>>>{}", e);
            return RestResult.error("9999", e.getLocalizedMessage());
        }
    }

    @Override
    public List<Long> queryDeptIdListByUserId(Long id) {
        return sysDeptMapper.queryDeptIdListByUserId(id);
    }

    @Override
    public RestResult<MemStoreResponse> getStoreInfoByDeptId(Long id) {
        return RestResult.success(sysDeptMapper.getStoreInfoByDeptId(id));
    }

    @Override
    public List<Long> getDeptIdsByStroreIdOrMerchantIdAndType(List<Long> businessIds, Integer deptType) {
        return sysDeptMapper.getDeptIdsByStroreIdOrMerchantIdAndType(businessIds,deptType);
    }

    @Override
    public RestResult<MerchantResponse> getMerchantByDeptId(Long Id) {
        return RestResult.success(sysDeptMapper.getMerchantByDeptId(Id));
    }

    @Override
    public SysDept getByIdPid(Long id) {
        log.info("入参为：{}", JSON.toJSONString(id));
        //根据id查询到对应的类型
        SysDept byIdPid = sysDeptMapper.getByIdPid(id);
        if(id==0){
            throw new AppRuntimeException("参数为空");
        }
        if(byIdPid==null){
          throw new AppRuntimeException("不存在");
        }
        if(byIdPid.getDeptType()!=0){
            byIdPid=  getByIdPid(byIdPid.getPid());
        }

        return byIdPid;
    }



   /* public TblCategory getParentCategoryObject(TblCategory category) {
        if (category.getParentId() == 1) {
            return category;
        }

        TblCategory tblCategory = allCategory.stream().filter(
                x -> Objects.equals(x.getCategoryId(), category.getParentId())
        ).findFirst().get();

        return getParentCategoryObject(tblCategory);
    }
        return RestResult.success(sysDeptMapper.getByIdPid(id));
}*/

}
